package com.moli.iov.task.remoting.op.reponse;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.task.constants.Constants;
import com.moli.iov.task.model.domain.Page;
import com.moli.iov.task.model.dto.VehicleBaseInfoDto;
import com.moli.iov.util.HttpUtil;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * OP车辆数据
 * </p>
 *
 * @Auther: zql
 * @Date: 2019/1/7 15:06
 */
@Slf4j
@Component
public class VehicleBaseResponseHandler {

    @Autowired
    private TokenResponseHandler tokenRequestHandler;

    @Value("${op_query_vehicle_base_url}")
    private String opQueryVehicleBaseUrl;

    @Value("${op_channel_val}")
    private String opChannelVal;

    /**
     * 获取OP 车辆数据
     * @return
     */
    public Page<VehicleBaseInfoDto> queryOpehicleBaseInfo( List<String> vinsList,
                                                           int pageNo,
                                                           int pageSize) throws IOException {
        String token = tokenRequestHandler.getToken();
        return this.queryOpehicleBaseInfoReal(token, vinsList, String.valueOf(pageNo), String.valueOf(pageSize));
    }

    /***
     * 获取OP 车辆数据
     * @param token
     * @return
     * @throws Exception
     */
    public Page<VehicleBaseInfoDto> queryOpehicleBaseInfoReal(String token,
                                                              List<String> vinsList,
                                                              String pageNo,
                                                              String pageSize) throws IOException {
        Map<String, Object> params = Maps.newHashMap();

        params.put("vinsList", vinsList);
        params.put("pageNum", pageNo);
        params.put("pageSize", pageSize);

        Map<String, String> headers = Maps.newHashMap();
        headers.put("token", token);
        headers.put("channel", opChannelVal);
        String result = HttpUtil.postJson(opQueryVehicleBaseUrl, JSONObject.toJSONString(params
        ), headers);

        if(StringUtil.isBlank(result)){
            log.error("真实获取OP 车辆数据失败， OP返回空");
            throw new BusinessException("获取OP车辆数据异常");
        }

        JSONObject jsonObject = JSONObject.parseObject(result);

        if(Constants.OP_SUCCESS != jsonObject.getInteger("code")){
            log.error("真实获取OP 车辆数据失败，OP返回状态非200 token:{} 出参：{}",token, jsonObject);
            throw new BusinessException("真实获取OP 车辆数据失败，OP返回状态非200");
        }

        return jsonObject.getObject("data", Page.class);
    }
}
